import React, { useMemo } from 'react'
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts'
import { STAT_COLORS } from '../../../constant'
import { QuestionStatPropsType } from './interface'

function format(n: number): string {
  return (n * 100).toFixed(2)
}

const StatComponent: React.FC<QuestionStatPropsType> = ({ stat = [] }) => {
  const sum = useMemo(() => {
    return stat.reduce((prev, curr) => {
      return prev + curr.count
    }, 0)
  }, [stat])
  return (
    <div style={{ width: '300px', height: '400px' }}>
      <ResponsiveContainer width="100%" height="100%">
        <PieChart>
          <Pie
            dataKey="count"
            data={stat}
            cx="50%"
            cy="50%"
            outerRadius={50}
            fill="#8884d8"
            label={i => `${i.name}: ${format(i.count / sum)}%`}
          >
            {stat.map((i, index) => {
              return <Cell key={index} fill={STAT_COLORS[index]}></Cell>
            })}
          </Pie>
          <Tooltip></Tooltip>
        </PieChart>
      </ResponsiveContainer>
    </div>
  )
}

export default StatComponent
